# Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
# -------------------------------------------------------------
# This makefile defines the following targets

#   - docker - builds a did-service and did-db docker image
#   - did-db-docker - build did-db docker image
#   - did-service-docker - build did-data docker image
include docker-env.mk

# Disable implicit rules
.SUFFIXES:
MAKEFLAGS += --no-builtin-rules

BUILD_DIR ?=build

ARCH=$(shell go env GOARCH)
MARCH=$(shell go env GOOS)-$(shell go env GOARCH)

RELEASE_IMAGES = did-db did-service
RELEASE_PLATFORMS = darwin-amd64 linux-amd64 windows-amd64

.DEFAULT_GOAL := all

.PHONY: all
all: docker did-service did-db
.PHONY: docker
docker: $(RELEASE_IMAGES:%=%-docker)
.PHONY: did-service
did-service: $(BUILD_DIR)/images/did-service/$(DUMMY)
.PHONY: did-db
baas-db: $(BUILD_DIR)/images/did-db/$(DUMMY)


.PHONY: $(RELEASE_IMAGES:%=%-docker)
$(RELEASE_IMAGES:%=%-docker): %-docker: $(BUILD_DIR)/images/%/$(DUMMY)

$(BUILD_DIR)/images/%/$(DUMMY):
		@echo "Building Docker image $(DOCKER_NS)/$*"
		@mkdir -p $(@D)
		$(DBUILD) -f $(BUILD_DIR)/images/$*/Dockerfile \
				--build-arg GO_VER=$(GO_VER) \
				--build-arg ARCH=$(ARCH) \
				$(BUILD_ARGS) \
				-t $(DOCKER_NS)/$* .
		docker tag $(DOCKER_NS)/$*  $(DOCKER_NS)/$*:$(BASE_VERSION)
		@touch $@

.PHONY: docker-clean
docker-clean: $(RELEASE_IMAGES:%=%-docker-clean)
%-docker-clean:
		-@for image in "$$(docker images --quiet --filter=reference='$(DOCKER_NS)/$*:$(DOCKER_TAG)')"; do \
				[ -z "$$image" ] || docker rmi -f $$image; \
		done
		-@rm -rf $(BUILD_DIR)/images/$*/.dummy* || true
